package org.jks.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Date;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

public class ExportUtil {
	public static final VelocityEngine ve = new VelocityEngine(); 
	public static final VelocityContext context = new VelocityContext();
	public static final Properties properties = new Properties();
	public static Template template;
	public static Writer wt;
	
	public static void export(HttpServletResponse response, String templatePath, String templateName, 
			String filename, String format, Object data){
		properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatePath);
		try{
			filename =  java.net.URLEncoder.encode(filename, "UTF-8") + "-"
					+ DateUtil.toString(new Date(), "yyyyMMddHHmmss") + "."
					+ format;
		}
		catch(Exception e){
			filename = DateUtil.toString(new Date(), "yyyyMMddHHmmss") + "."
					+ format;
		}
		
		ve.init(properties);
		template = ve.getTemplate(templateName, "utf-8"); 
		context.put("data", data);  
		response.setContentType(FileUtil.contentTypes.get(format));
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + filename);
		try{
			PrintWriter wt = response.getWriter();
			template.merge(context, wt);  
		    wt.flush(); 
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void generate(String path, String templatePath, String templateName, Object data) throws IOException{
		properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatePath);
		ve.init(properties);
		template = ve.getTemplate(templateName, "utf-8"); 
		context.put("data", data);  
		File file = new File(path);  
	    if (file.exists()) {  
	    	//清空内容
	        FileWriter emptyWriter = new FileWriter(file);  
	        wt = new BufferedWriter(emptyWriter);  
	        wt.write("");  
	    } else {  
	        file.createNewFile();  
	    }  
	    FileOutputStream outfile = new FileOutputStream(file);  
	    wt = new PrintWriter(outfile);  
	    template.merge(context, wt);  
	    wt.flush();
	    wt.close();
	}
}
